package com.py.nginxanalysis.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.py.nginxanalysis.model.RunTimeEntity;

import java.io.*;
import java.sql.*;
import java.util.ResourceBundle;

public class AnalysisUtil {

    //超时文件解析
    public static int runTimeAnalysis(int recordNum,String filePath)  {
        System.out.println("从第"+recordNum+"行开始解析");
        ResourceBundle resource = ResourceBundle.getBundle("path");  // 读取自定义配置文件
        String url = resource.getString("path.databaseUrl");
        String id = resource.getString("path.user");
        String password = resource.getString("path.password");
        FileReader in = null;
        LineNumberReader reader = null;
        String rowContent = "";
        Connection conn = null;
        Statement statement = null;
        int lineNum = 0; // 当前行数


        try {
            in= new FileReader(filePath);
            reader= new LineNumberReader(in);
            conn = DriverManager.getConnection(url, id, password);
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }

        // 日志读取逻辑
        while(rowContent!=null) {
            try {
                lineNum++;
                rowContent = reader.readLine();
                if (lineNum > recordNum && rowContent != null && rowContent.charAt(0) != '*') {
                    JSONObject json = JSONObject.parseObject(rowContent);
                    RunTimeEntity entity = JSON.toJavaObject(json, RunTimeEntity.class);
                    System.out.println(lineNum + "行:" + entity.getHost() + "&&" + entity.getMethod());
                    String sql = "insert into runtime_analysis values('" + entity.getTime() + "','" + entity.getHost() + "','" + entity.getForaddr() +  "','" + entity.getMethod() +
                            "','" + entity.getTenantID() +  "','" + entity.getReqTime()+"')";
//                    System.out.println(sql);
                    statement = conn.createStatement();
                    statement.execute(sql);
                }
            }
            catch (SQLException | IOException throwables) {
                throwables.printStackTrace();
            }
        }
        try {
            conn.close();
            reader.close();
            in.close();
        } catch (IOException | SQLException e) {
            e.printStackTrace();
        }
        return lineNum-1;
    }


}
